package com.company.soft;

import java.util.ArrayList;
import java.util.List;
import com.company.adapter.GridViewAdapter;
import com.company.adapter.ListViewAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements Runnable,
		OnItemClickListener {
	private static final int FIRST = 0;
	private static final int SECOND = 1;
	
	private static final int SEARCH_APP = 0;
	
	private ProgressDialog pd = null;
	
	private List<PackageInfo> packageInfos = null;
	private List<PackageInfo> userPackageInfo = null;
	private List<PackageInfo> showPackageInfos;
	
	private ImageButton imageButton1 = null;
	private ImageButton imageButton2 = null;
	
	private boolean allApplication = false;
	private boolean isListView = false;
	
	private ListView lv = null;
	private GridView gv = null;
	

   //处理从子线程中传出来的数据
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == SEARCH_APP) {
				showPackageInfos = packageInfos;
				gv.setAdapter(new GridViewAdapter(MainActivity.this,
						showPackageInfos));
				lv.setAdapter(new ListViewAdapter(MainActivity.this,
						showPackageInfos));
				pd.dismiss();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 取消title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.main);
		
		gv = (GridView) this.findViewById(R.id.apps_gridview);
		lv = (ListView) this.findViewById(R.id.lv_listview);
		// 网格空间触发的事件
		gv.setOnItemClickListener(this);
		lv.setOnItemClickListener(this);
		lv.setCacheColorHint(0);
		imageButton1 = (ImageButton) this.findViewById(R.id.iv1_imageview);
		imageButton1.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (isListView) {
					imageButton1.setImageResource(R.drawable.grids);

					Toast.makeText(MainActivity.this, R.string.show_gridview,
							Toast.LENGTH_SHORT).show();
					lv.setVisibility(View.GONE);
					gv.setVisibility(View.VISIBLE);
					isListView = false;
					
					//动画效果
					Animation animation = new RotateAnimation(60, 0);
					animation.setDuration(200);//持续时间
					gv.startAnimation(animation);//给视图应用动画效果
				} else {
					Toast.makeText(MainActivity.this, R.string.table_gridview,
							Toast.LENGTH_SHORT).show();

					imageButton1.setImageResource(R.drawable.list);
					lv.setVisibility(View.VISIBLE);
					gv.setVisibility(View.GONE);
					
					Animation animation = new TranslateAnimation(130, 1, 130, 1);
					animation.setDuration(200);//持续时间
					lv.startAnimation(animation);//给视图应用动画效果
					
					isListView = true;
					
				}
			}
		});
		imageButton2 = (ImageButton) this.findViewById(R.id.iv2_imageview);
		imageButton2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (allApplication) {
					showPackageInfos = packageInfos;
					allApplication = false;
					Toast.makeText(MainActivity.this, R.string.show_all,
							Toast.LENGTH_SHORT).show();

				} else {
					showPackageInfos = userPackageInfo;
					allApplication = true;
					Toast.makeText(MainActivity.this, R.string.show_user,
							Toast.LENGTH_SHORT).show();
				}
				gv.setAdapter(new GridViewAdapter(MainActivity.this,
						showPackageInfos));
				lv.setAdapter(new ListViewAdapter(MainActivity.this,
						showPackageInfos));
			}

		});
		String progress1 = getResources().getString(R.string.progress1);
		String progress2 = getResources().getString(R.string.progress2);
		pd = ProgressDialog.show(this, progress1, progress2, true, false);

		Thread t = new Thread(this);
		t.start();
	}
	
	public void run() {
		packageInfos = getPackageManager().getInstalledPackages(
				PackageManager.GET_UNINSTALLED_PACKAGES
						| PackageManager.GET_ACTIVITIES);
		userPackageInfo = new ArrayList<PackageInfo>();

		for (int i = 0; i < packageInfos.size(); i++) {
			PackageInfo temp = packageInfos.get(i);
			ApplicationInfo appInfo = temp.applicationInfo;
			boolean flag = false;
			/*
			 * 查看系统源代码得到！
			 */
			if ((appInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
				flag = true;
			} else if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				flag = true;
			}
			if (flag) {
				userPackageInfo.add(temp);
			}
		}
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 向主线程发送消息
		mHandler.sendEmptyMessage(SEARCH_APP);
	}

	// 点击选项触发的事件
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		final PackageInfo tempInfo = showPackageInfos.get(position);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.option);
		String[] arrays = getResources().getStringArray(R.array.arrays);
		builder.setItems(arrays, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					String packageName = tempInfo.packageName;
					ActivityInfo activityInfo = tempInfo.activities[0];// 取出activity
					if (activityInfo == null) {
						Toast.makeText(MainActivity.this, R.string.response,
								Toast.LENGTH_SHORT);
						return;
					}
					String activityName = activityInfo.name;
					Intent intent = new Intent();
					intent.setComponent(new ComponentName(packageName,
							activityName));
					startActivity(intent);
					break;
				case 1:
					showAppDetail(tempInfo);
					break;
				case 2:
					Uri packageUri = Uri.parse("package:"
							+ tempInfo.packageName);
					Intent deleteIntent = new Intent();
					deleteIntent.setAction(Intent.ACTION_DELETE);
					deleteIntent.setData(packageUri);
					startActivityForResult(deleteIntent, 0);
					break;
				}
			}

		});
		builder.setNegativeButton(R.string.cancel, null);
		builder.create().show();
	}

	private void showAppDetail(PackageInfo tempInfo) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.information);
		StringBuffer message = new StringBuffer();
		String programName = getResources().getString(R.string.program_name);
		message.append(programName
				+ tempInfo.applicationInfo.loadLabel(getPackageManager()));
		String packageName = getResources().getString(R.string.package_name);
		String versionNum = getResources().getString(R.string.version_num);
		String versionName = getResources().getString(R.string.version_name);
		message.append("\n " + packageName + ":" + tempInfo.packageName);
		message.append("\n " + versionNum + ":" + tempInfo.versionCode);
		message.append("\n " +versionName + ":" + tempInfo.versionName);

		builder.setMessage(message.toString());
		builder.setIcon(tempInfo.applicationInfo.loadIcon(getPackageManager()));
		builder.setPositiveButton(R.string.sure, null);
		builder.create().show();

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		packageInfos = getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_ACTIVITIES);
		userPackageInfo = new ArrayList<PackageInfo>();
		for (int i = 0; i < packageInfos.size(); i++) {
			
			PackageInfo temp = packageInfos.get(i);
			ApplicationInfo appInfo = temp.applicationInfo;
			boolean flag = false;
			if((appInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
				flag = true;
			} else if((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				flag = true;
			}
			if(flag) {
				userPackageInfo.add(temp);
			}
		}
		
		if(allApplication) {
			showPackageInfos = packageInfos;
		} else {
			showPackageInfos = userPackageInfo;
		}
		
		gv.setAdapter(new GridViewAdapter(MainActivity.this,showPackageInfos));
		lv.setAdapter(new ListViewAdapter(MainActivity.this,showPackageInfos));
			
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, FIRST, 0, R.string.help);
		menu.add(0, SECOND, 1, R.string.exit);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case FIRST:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle( R.string.help);
				builder.setMessage(R.string.content);
				builder.setPositiveButton(R.string.sure, null);
				builder.create().show();
				break;
			case SECOND:
				finish();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
}